<?php

namespace Application;

use Zend_Auth;
use Admin\AuthAdapter;
use Zend_Auth_Adapter_Interface;

abstract class AdminAbstract extends ControllerAbstract
{
    /*** @var Zend_Auth_Adapter_Interface */
    protected $authAdapter;

    public function callAction($action)
    {
        if ($action != 'login') {
            $this->authenticate();
        }
        parent::callAction($action);
    }

    protected function authenticate()
    {
        $auth = Zend_Auth::getInstance();
        $loginUrl = 'admin/login';
        if (!$auth->hasIdentity()) {
            $this->redirect($loginUrl);
            return;
        }
        $authAdapter = $this->getAuthAdapter()
            ->setIdentity($auth->getIdentity()->userName)
            ->setCredential($auth->getIdentity()->credential);
        if (!$authAdapter->authenticate()->isValid()) {
            $auth->clearIdentity();
            $this->redirect($loginUrl);
        }
    }

    public function getAuthAdapter()
    {
        if (null === $this->authAdapter) {
            $this->setAuthAdapter(new AuthAdapter(Db::getInstance()));
        }
        return $this->authAdapter;
    }

    /*** @param mixed $authAdapter */
    public function setAuthAdapter(Zend_Auth_Adapter_Interface $authAdapter)
    {
        $this->authAdapter = $authAdapter;
    }
}
